package com.vxdata.common.utils.base64;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.IoUtil;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HutoolBase64ToMultipartFile implements MultipartFile {

    private final byte[] content;
    private final String contentType;
    private final String originalFilename;

    /**
     * 构造函数，将Base64字符串转换为MultipartFile对象
     *
     * @param base64String     Base64编码的字符串
     * @param contentType      文件类型（如 "image/png"）
     * @param originalFilename 文件原始名称
     */
    public HutoolBase64ToMultipartFile(String base64String, String contentType, String originalFilename) {
        Objects.requireNonNull(base64String, "Base64 string cannot be null");
        Objects.requireNonNull(contentType, "Content type cannot be null");
        Objects.requireNonNull(originalFilename, "Original filename cannot be null");

        // 正则表达式匹配data URI scheme前缀
        Pattern pattern = Pattern.compile("^data:([^;]+);base64,(.*)$");
        Matcher matcher = pattern.matcher(base64String);

        if (matcher.find()) {
            this.contentType = matcher.group(1);
            this.content = Base64.decode(matcher.group(2));
        } else {
            this.contentType = contentType;
            this.content = Base64.decode(base64String);
        }
        this.originalFilename = originalFilename;
    }

    @Override
    public String getName() {
        return "base64ConvertedFile"; // 可以根据需要自定义
    }

    @Override
    public String getOriginalFilename() {
        return originalFilename;
    }

    @Override
    public String getContentType() {
        return contentType;
    }

    @Override
    public boolean isEmpty() {
        return content.length == 0;
    }

    @Override
    public long getSize() {
        return content.length;
    }

    @Override
    public byte[] getBytes() throws IOException {
        return content;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(content);
    }

    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        if (dest == null) {
            throw new IllegalArgumentException("Destination file cannot be null");
        }

        try (InputStream in = getInputStream();
             OutputStream out = new FileOutputStream(dest)) {
            IoUtil.copy(in, out);
        } catch (IOException e) {
            throw new IOException("Failed to transfer file to " + dest.getAbsolutePath(), e);
        }
    }

    /**
     * 静态工厂方法
     *
     * @param base64String     Base64编码的字符串
     * @param contentType      文件类型
     * @param originalFilename 文件原始名称
     * @return
     */
    // 静态工厂方法，方便创建实例
    public static MultipartFile fromBase64(String base64String, String contentType, String originalFilename) {
        return new HutoolBase64ToMultipartFile(base64String, contentType, originalFilename);
    }

    public static void main(String[] args) {
        // 假设这是你的Base64编码的字符串（这里为了演示，用了一个简单的例子）
        String base64String = "iVBORw0KGgoAAAANSUhEUgAA...";// 这里应该是完整的Base64编码字符串
        String contentType = "image/png"; // 文件类型
        String originalFilename = "example.png"; // 文件原始名称

        // 创建 MultipartFile 对象
        MultipartFile multipartFile = HutoolBase64ToMultipartFile.fromBase64(base64String, contentType, originalFilename);

        // 现在你可以像使用普通的 MultipartFile 一样使用这个对象了
        System.out.println("File size: " + multipartFile.getSize());
        System.out.println("Content type: " + multipartFile.getContentType());
        System.out.println("Original filename: " + multipartFile.getOriginalFilename());
    }
}